package com.project.personnel.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.project.personnel.dao.DepartmentMapper;
import com.project.personnel.entity.Department;
import com.project.personnel.service.DepartmentService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author diaominyh
 * @since 2022-12-12
 */
@RestController
@RequestMapping("/department")
public class DepartmentController {
    @Resource
    private DepartmentService departmentService;
    @Resource
    private DepartmentMapper departmentMapper;
    @GetMapping("/departmentCha")
    public List<Department> departmentList(@RequestParam("name") String name){
        return departmentService.listDempartment(name);
    }
    @GetMapping("/departmentDanCha/{name}")
    //隐藏域根据名字获取id
    public Integer departmentDanCha(@PathVariable String name){
        QueryWrapper<Department> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("name",name);
        Department  department=departmentMapper.selectOne(queryWrapper);
        int id=department.getId();
        return id;
    }
    @PostMapping("/departmentAdd/{id}/{name}")
    //添加部门
    public boolean departmentAdd(@PathVariable Integer id,@PathVariable String name){
        Department department=departmentService.getById(id);
        Department department1=new Department();
        department1.setName(name);
        department1.setParentId(id);
        department1.setEnabled(1);
        department1.setIsParent(0);
        boolean flag= departmentService.save(department1);
        if(flag){
            department.setIsParent(1);
            departmentService.updateById(department);
            String dian=".";
            String depPath=department.getDepPath()+dian+department1.getId();
            department1.setDepPath(depPath);
            departmentService.updateById(department1);
        }
        return flag;
    }
    @DeleteMapping("/departmentDelete/{id}")
    //删除部门
    public boolean departmentDelete(@PathVariable Integer id){
        int list=departmentService.list(id);
        boolean fiag=departmentService.removeById(id);
        int result=0;
        if(fiag){
            result=departmentService.deleteDepartment(id);
        }
        if(result>0 ||result==0){
            List<Department> list1=departmentService.listDep(list);
            if(list1.size()==0){
                Department department=departmentService.department(list);
                department.setIsParent(0);
                departmentService.updateById(department);
            }
            fiag=true;
            return fiag;
        }else {
            fiag=false;
            return fiag;
        }
    }

}

